<template>
  <div class="page-main" v-title data-title="流程步骤列表">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>流程步骤列表</span></div>
    <div class="container">
      <div class="header" style="padding: 10px 0px">
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :xl="{ span: 14 }" :lg="{ span: 11 }">
            <!-- <a-button class="hte-btn" plain @click="handleExport">导出</a-button> -->
            <a-button class="hte-btn" plain @click="handleReload">刷新</a-button>
          </a-col>
          <a-col :xl="{ span: 9 }" :lg="{ span: 13 }" class="input-ground">
            <a-input-search v-model="searchForm.keyword" @search="handleToSearch" placeholder="请按照关键字进行搜索" />
            <a-button class="hte-btn del-btn" @click="showSearchForm = true">高级查询</a-button>
          </a-col>
        </a-row>
         <a-modal
          :visible="showSearchForm"
          width="70vw"
          :bodyStyle="{ padding: '10px' }"
          title="高级查询"
          @ok="handleToSearch"
          @cancel="showSearchForm = false"
        >
          <a-form-model
            ref="ruleForm"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            @keyup.enter.native="handleToSearch"
          >
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="执行状态">
                  <a-select v-model="searchForm.status" style="width: 100%" allowClear>
                    <a-select-option value=""> 全部 </a-select-option>
                    <a-select-option value="0">未执行</a-select-option>
                    <a-select-option value="1">已处理</a-select-option>
                    <a-select-option value="2">已失败</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="流程Key">
                  <a-input allow-clear v-model="searchForm.flowKey" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业务主键">
                  <a-input allow-clear v-model="searchForm.businessKey" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-modal>
      </div>
      <div class="content-list">
        <a-table
          :columns="columns"
          :data-source="records"
          rowKey="id"
          bordered
          :pagination="false"
          :customRow="customRow"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="statusRender" slot-scope="text">
            <template v-if="text == 0"> 未执行 </template>
            <template v-if="text == 1"> 已处理 </template>
            <template v-if="text == 2"> 已失败 </template>
          </template>
          <template slot="actionRender" slot-scope="text, record">
            <a-button @click="resetTaskAfterHandler(record)">重新执行</a-button>
            <a-button @click="viewTaskAfterHandler(record)">查看参数</a-button>
          </template>
        </a-table>
        <a-pagination
          show-size-changer
          :default-current="1"
          :total="searchForm.total"
          @change="pageChange"
          @showSizeChange="onShowSizeChange"
          :show-total="(total) => `共 ${total} 条记录`"
        />
      </div>
    </div>
    <a-modal
      :forceRender="true"
      title="Json查看器"
      :visible="visible"
      :closable="false"
      @ok="visible = false"
      @cancel="visible = false"
      width="80vw"
      height="60vh"
    >
      <JsonEditor ref="jsonEditor" v-model="json"> </JsonEditor>
      <template slot="footer">
        <a-button type="primary" @click="handleSave">保存修改</a-button>
        <a-button @click="visible = false">直接关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { formatDate, parseTime } from '@/utils/util'
import { UtilsMixin } from '@/mixins/UtilsMixin'
import { TableMixin } from '@/mixins/TableMixin'
export default {
  mixins: [UtilsMixin, TableMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    JsonEditor: () => import('@/components/tools/JsonEditor'),
  },
  data() {
    return {
      visible: false,
      currUserId: this.$store.getters.userInfo.username,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      urls: {
        list: '/hteFlowStepInfo/page',
        edit: '/hteFlowStepInfo/edit',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      keywordType: '1',
      json: {},
      record: {},
      records: [],
      columns: [
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusRender' },
          width: '60px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '流程KEY',
          dataIndex: 'flowKey',
          width: '200px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '流程实例ID',
          dataIndex: 'id',
          width: '200px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '业务编码',
          dataIndex: 'businessKey',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '节点名称',
          dataIndex: 'taskName',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '节点标识',
          dataIndex: 'taskKey',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '当前处理人',
          dataIndex: 'userName',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '接收时间',
          dataIndex: 'acceptTime',
          align: 'center',
          width: '100px',
          ellipsis: true,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center',
          width: '100px',
          ellipsis: true,
        },
        {
          title: '操作',
          align: 'center',
          width: '180px',
          scopedSlots: { customRender: 'actionRender' },
        },
      ],
      showSearchForm: false,
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  async mounted() {
    this.fetchList()
  },
  methods: {
    fetchList() {
      postAction(this.urls.list, this.searchForm).then((res) => {
        if (res.success) {
          this.records = res.result.records
          this.$set(this.searchForm, 'total', res.result.total)
        } else {
          this.$message.error('查询数据错误:' + res.message)
        }
      })
    },

    handleReload() {
      this.fetchList()
    },
    handleToSearch() {
      this.searchForm.pageNo = 1
      this.showSearchForm = false
      this.fetchList()
    },
    handleExport() {
      this.searchForm.selectedIds = this.selectedRowKeys.join(',')
      let url = process.env.VUE_APP_API_BASE_URL + '/infrastructure/export?1=1'
      this.handleExportXls(parseTime(new Date(), '{y}{m}{d}') + '《基建现场管理单据列表》', url, this.searchForm)
    },
    pageChange(pageNo, pageSize) {
      this.$set(this.searchForm, 'pageSize', pageSize)
      this.$set(this.searchForm, 'pageNo', pageNo)
      this.fetchList()
    },
    onShowSizeChange(pageNo, pageSize) {
      this.searchForm.pageNo = 1
      this.searchForm.pageSize = pageSize
      this.fetchList()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    customRow(record) {
      return {
        on: {
          dblclick: (event) => {
            if (!this.selectedRowKeys) {
              this.selectedRowKeys = []
              this.selectedRows = []
            }
            if (this.selectedRowKeys.indexOf(record.id) <= -1) {
              this.selectedRows.push(record)
              this.selectedRowKeys.push(record.id)
            } else {
              let index = this.selectedRowKeys.indexOf(record.id)
              this.selectedRowKeys.splice(index, 1)
              this.selectedRows.splice(index, 1)
            }
          },
        },
      }
    },
    resetTaskAfterHandler(record) {
      this.record = record
      this.json = JSON.parse(record.taskAfterHandlerVo)
      getAction(this.urls.checkIsNew + '?id=' + record.id).then((res) => {
        if (res.success) {
          if (res.result > 0) {
            this.confirmRest(
              '当前记录并不是流程KEY[' +
                record.flowKey +
                ']业务主键[' +
                res.businessKey +
                ']的最新记录，是否继续执行重新执行'
            )
          } else {
            this.confirmRest('请确认是否重新执行[' + record.flowKey + ']业务主键[' + record.businessKey + ']')
          }
        } else {
          that.$message.success('执行失败:' + res.message)
        }
      })
    },
    confirmRest(content) {
      let that = this
      this.$confirm({
        content: content,
        onOk: () => {
          that.record.status = 0
          that.record.dealCount = 0
          that.record.remark = '重新执行'
          that.handleSave()
        },
      })
    },
    viewTaskAfterHandler(record) {
      this.record = record
      this.json = JSON.parse(record.taskAfterHandlerVo)
      this.visible = true
    },
    handleSave() {
      this.visible = false
      let json = this.$refs.jsonEditor.getValue()
      if (json) {
        let jsonStr = JSON.stringify(json)
        json = json.replace('"', '"')
        json = json.replace('\n', '')
        json = json.replace('\t', '')
        this.record.taskAfterHandlerVo = json
      }

      postAction(this.urls.edit, this.record).then((res) => {
        if (res.success) {
          this.$message.success('保存成功')
          this.fetchList()
        } else {
          this.$message.success('保存失败:' + res.message)
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .container {
    .content {
      margin-top: 20px;

      section {
        margin-bottom: 18px;

        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }

          /deep/ .a-upload__input {
            display: none !important;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}

/deep/ .el-upload__input {
  display: none !important;
}
</style>
